
package org.itboys.mobile.service.mongo.front;

import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SystemDictionaryService;

import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayMemberDto;
import org.itboys.mobile.dto.count.SundayCountDto;
import org.itboys.mobile.dto.count.SundayCountProductDto;
import org.itboys.mobile.dto.count.SundayCountTotalDto;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.promotion.SundayCoupon;
import org.itboys.mobile.service.mysql.front.SundayFrontCouponService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_结算_service_移动端
 */

@Service
public class SundayFrontCountService{
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private SundayFrontCartService cartService;
    @Autowired
    private SundayFrontMemberService memberService;

    @Autowired
    private SundayFrontCouponService couponService;
    @Autowired
    private SystemDictionaryService dictionaryService;
    /**
     * 购物车结算。双版本通用
     * @param memberId
     * @param cartIds
     * @param isUseAiGou 是否使用爱购币,只针对shopId=0的直营商品。type==6或type==10隐藏
     * @param isUseBalance 是否使用余额,只针对shopId=0的直营商品。type==6或type==10隐藏
     *  @param isUseBalance 是否使用余额,只针对shopId=0的直营商品。type==6或type==10隐藏
     * @param teamIsJoin 是否参与拼团,只针对shopId=0的直营商品。0单独购买，1参与别人的，2自己开团
     * @param teamGroupId 拼团组ID,只针对shopId=0的直营商品
     * @param sendType 1门店配送（默认），2自提。
     * @return
     */
   public SundayCountTotalDto countCart(Long memberId,List<Long> cartIds,

                                         Integer isUseAiGou,
                                         Integer isUseBalance,
                                         Integer isUsedConch,
                                         Integer teamIsJoin,
                                         Long teamGroupId,Integer sendType){
       //初始化默认参数，避免空指针异常
       isUseAiGou=isUseAiGou==null?0:isUseAiGou;
       isUseBalance=isUseBalance==null?0:isUseBalance;
       teamIsJoin=teamIsJoin==null?0:teamIsJoin;
       teamGroupId=teamGroupId==null?0l:teamGroupId;
       sendType=sendType==null?1:sendType;
       //查询用户钱包，等级信息
       SundayMemberDto memberDto = memberService.packageDtoSingle(null, memberId,true,false);
       logger.info("--------开始结算-用户等级"+memberDto.getGrade()+"-用户折扣---"+memberDto.getDiscount());
       //获取需要结算的信息
        SundayCountTotalDto countTotalDto = cartService.getCart(memberId,cartIds,null);
        //Sunday
        //循环出自营或外部商家
        for(SundayCountDto countDto:countTotalDto.getCounts()){
            //2018年2月8日，新增，以用户的折扣重新核算总价（核算商品价格）。只对自营结算有效
            if(LongUtil.isZreo(countDto.getShopId())){
                BigDecimal discount = memberDto.getDiscount();
                if(discount.compareTo(new BigDecimal("1"))==-1){
                    logger.info("当前用户属于折扣用户");
                    Double _payAmount = 0.00;
                    for(SundayCountProductDto countProductDto:countDto.getProducts()){
                        BigDecimal _price= countProductDto.getPrice();
                        //判断商品是否有折扣
                        if(countProductDto.getIsDiscount()==1){
                            _price = countProductDto.getPrice().multiply(discount);
                        }
                        _payAmount+=_price.doubleValue()*countProductDto.getNum();
                        countProductDto.setPrice(_price);
                    }
                    countDto.setPayAmount(new BigDecimal(_payAmount));
                    //countDto.setTotalAmount(new BigDecimal(_payAmount));
                }
            }




            //结算信息说明
            String info ="";
            //实付金额
            BigDecimal payAmount =countDto.getPayAmount();
            //运费
            BigDecimal sendAmount =new BigDecimal("0.00");
            String sendAmountMsg ="";

           /************ 自营，有且只有一个*********************/
            if(LongUtil.isZreo(countDto.getShopId())){
                //门店配送
                //配置运费。自营产品。运费字典读取
                if(sendType==SundayCommonConstants.send_type_send){
                    SystemDictionary sendAmountDic =dictionaryService.getDictionaryByKey2("sendAmount");
                    BigDecimal _baseAmount = new BigDecimal(sendAmountDic.getName());
                    BigDecimal _sendAmount =new BigDecimal(sendAmountDic.getValue());

                    if(_baseAmount.compareTo(payAmount)==1){
                        sendAmount=_sendAmount;
                    }
                    sendAmountMsg = sendAmountDic.getDesc();
                }else if(sendType==SundayCommonConstants.send_type_self){
                    sendAmount=new BigDecimal("0.00");
                    sendAmountMsg="自提免邮费";
                }

                //实付加上运费,以下场景不需要运费:爱购币兑换
                //
                if(countDto.getType()!= SundayCommonConstants.type_aigou){
                    payAmount=payAmount.add(sendAmount);
                }





                 BigDecimal aiGouTotalCoin = memberDto.getAigouCoin();
                 //海淘结算，带出用户身份证号码
                if(countDto.getType()==SundayCommonConstants.type_haitao){
                    //2018年1月28日，取消
                   /* SundayMember member=memberService.getById(memberId);
                    countDto.setIdCard(member.getIdCard());
                    countDto.setRealName(member.getRealName());
                    //实付金额加上关税
                   payAmount=payAmount.add(countDto.getProducts().get(0).getTax());
                   //结算信息
                    info=countDto.getProducts().get(0).getTaxMsg();*/
                 //秒杀结算
                }else if(countDto.getType()==SundayCommonConstants.type_miaosha){

                //拼团结算
                }else if(countDto.getType()==SundayCommonConstants.type_pintuan){
                    //在结算中显示拼团商品价格
                    //0单独购买，1参与别人的，2自己开团
                    if(teamIsJoin==0){
                        //原价teamPrice,临时用一下，结算中使用，赋值到了teamPrice上
                        countDto.getProducts().get(0).setPrice(countDto.getProducts().get(0).getTeamPrice());
                        //2018年1月31日，特殊计算总价
                          payAmount=countDto.getProducts().get(0).getTeamPrice();
                    }

                    //拼团价格(已在列表中处理)
                    countDto.setTeamIsJoin(teamIsJoin);
                    countDto.setTeamGroupId(teamGroupId);
                    info="如果有效时间内拼团不成功，支付金额将退回的到您的钱包中。";
                }


                //2018年2月4日，排除爱购币兑换
                //2018年3月5日，使用抵扣手段。以下场景不能使用：爱购币兑换，达人试用
                if(countDto.getType()!=SundayCommonConstants.type_aigou&&countDto.getType()!=SundayCommonConstants.type_shiyong) {
                    //按顺序使用，爱购币,优惠券,使用爱购币
                    //初始化抵扣变量
                    countDto.setIsUseAigou(0);
                    countDto.setIsUseBalance(0);
                    //1，使用爱购币，
                    //用户总的爱购币

                    countDto.setAiGouTotalCoin(aiGouTotalCoin);
                    logger.info("--------用户持有爱购币=" + aiGouTotalCoin);
                    //爱购币可用数量=实付金额*可用比例
                    BigDecimal aiGouAbleCoin = payAmount.multiply(memberDto.getChargeDiscountAgCoin());
                    logger.info("--------本次预计可用爱购币=" + aiGouAbleCoin + ",折算比例：" + memberDto.getChargeDiscountAgCoin());
                    //判断用户是否有足够的爱购币,
                    //足够多。全部使用用户的爱购币
                    if (aiGouTotalCoin.compareTo(aiGouAbleCoin) != -1) {
                        aiGouAbleCoin = aiGouAbleCoin;
                    } else {
                        aiGouAbleCoin = aiGouTotalCoin;
                    }
                    logger.info("--------本次实际可用爱购币=" + aiGouAbleCoin + ",折算比例：" + memberDto.getChargeDiscountAgCoin());
                    //爱购币可用对应的金额
                    BigDecimal aiGouAbleAmount = aiGouAbleCoin.divide(memberDto.getChangeAmountAgCoin());
                    logger.info("--------本次实际可用爱购币兑换现金=" + aiGouAbleAmount + ",折算比例：" + memberDto.getChangeAmountAgCoin());
                    //如果爱购币折算的现金不足1就显示为0，
                    if (aiGouAbleAmount.compareTo(new BigDecimal(1)) == 1) {
                        //爱购币对应现金。理论是1：100，可配置
                        //使用爱购币
                        if (isUseAiGou == SundayCommonConstants.YES) {
                            payAmount = payAmount.subtract(aiGouAbleAmount);
                            //记录使用的爱购币数量,和抵扣金额
                            countDto.setAiGouUsedCoin(aiGouAbleCoin);
                            countDto.setAiGouUsedAmount(aiGouAbleAmount);
                        }
                        //爱购币不足就强制默认爱购币抵扣手段
                    } else {
                        aiGouAbleCoin = new BigDecimal("0");
                        aiGouAbleAmount = new BigDecimal("0");
                        isUseAiGou = 0;
                    }
                    countDto.setIsUseAigou(isUseAiGou);
                    countDto.setAiGouAbleCoin(aiGouAbleCoin);
                    countDto.setAiGouAbleAmount(aiGouAbleAmount);
                    //2，使用优惠券，
                    SundayCoupon coupon = couponService.getOptimalCoupon(memberId, payAmount);
                    if (coupon != null) {
                        payAmount = payAmount.subtract(coupon.getDecuAmount());
                        countDto.setCouponId(coupon.getId());
                        countDto.setCouponAmount(coupon.getDecuAmount());
                        countDto.setCouponMsg("优惠券扣减" + coupon.getDecuAmount() + "元");
                    }else{
                        countDto.setCouponId(0l);
                        countDto.setCouponAmount(new BigDecimal("0.00"));
                    }
                    //3，使用余额。
                    //余额
                    BigDecimal balanceAbleAmount = memberDto.getTotalAmount();
                    logger.info("用户可用余额：" + balanceAbleAmount);
                    countDto.setBalanceAbleAmount(balanceAbleAmount);
                    logger.info("是否使余额=" + isUseBalance);
                    BigDecimal balanceUsedAmount = new BigDecimal("0");
                    //判断余额是否>0
                    if (balanceAbleAmount.compareTo(new BigDecimal(0)) == 1) {
                        logger.info("开始使用余额");
                        //是否使用余额
                        if (isUseBalance == SundayCommonConstants.YES) {
                            /***********重要*********判断余额和实付金额的关系************/
                            //如果余额大于实付金额
                            if (balanceAbleAmount.compareTo(payAmount) != -1) {
                                logger.info("余额足够");
                                balanceUsedAmount = payAmount;
                                payAmount = new BigDecimal("0");

                                //如果余额小于实付金额
                            } else {
                                logger.info("余额不够");

                                payAmount = payAmount.subtract(balanceAbleAmount);
                                balanceUsedAmount = balanceAbleAmount;

                            }
                        }
                        //余额不足就强制默认爱余额抵扣手段

                    } else {
                        balanceAbleAmount = new BigDecimal(0);
                        isUseBalance = 0;
                    }

                    countDto.setIsUseBalance(isUseBalance);
                    countDto.setBalanceAbleAmount(balanceAbleAmount);
                    countDto.setBalanceUsedAmount(balanceUsedAmount);
                    //4，使用贝壳抵扣。
                    BigDecimal conchAbleAmount = memberDto.getConch();
                    logger.info("用户可用贝壳：" + conchAbleAmount);
                    countDto.setConchAbleAmount(conchAbleAmount);
                    logger.info("是否使用贝壳=" + isUsedConch);
                    BigDecimal conchUsedAmount = new BigDecimal("0");
                    //判断余额是否>0
                    if (conchAbleAmount.compareTo(new BigDecimal(0)) == 1) {
                        logger.info("开始使用贝壳");
                        //是否使用余额
                        if (isUsedConch == SundayCommonConstants.YES) {
                            /***********重要*********判断贝壳余额和实付金额的关系************/
                            //如果余额大于实付金额
                            if (conchAbleAmount.compareTo(payAmount) != -1) {
                                logger.info("贝壳足够");
                                conchUsedAmount = payAmount;
                                payAmount = new BigDecimal("0");

                                //如果余额小于实付金额
                            } else {
                                logger.info("贝壳不够");

                                payAmount = payAmount.subtract(conchAbleAmount);
                                conchUsedAmount = conchAbleAmount;
                            }
                        }
                        //贝壳不足就强制默认爱贝壳抵扣手段
                    } else {
                        conchAbleAmount = new BigDecimal(0);
                        isUsedConch = 0;
                    }

                    countDto.setIsUseConch(isUsedConch);
                    countDto.setConchAbleAmount(conchAbleAmount);
                    countDto.setConchUsedAmount(conchUsedAmount);
                }else{
                    countDto.setAiGouTotalCoin(aiGouTotalCoin);
                }

            }else{
                //其他商家运费自定义
                SundayMember shop= memberService.getById(countDto.getShopId());
               // SystemDictionary sendAmountDic =dictionaryService.getDictionaryByKey2("sendAmount");
                BigDecimal _baseAmount = new BigDecimal(shop.getSendAmountBase());
                BigDecimal _sendAmount =new BigDecimal(shop.getSendAmount());

                if(_baseAmount.compareTo(payAmount)==1){
                    sendAmount=_sendAmount;
                }
                sendAmountMsg ="满"+_baseAmount+"元免邮费";
                payAmount=payAmount.add(sendAmount);
                sendType=SundayCommonConstants.send_type_send;
                logger.info("结算门店-"+countDto.getShopName()+",结算类型="+countDto.getType());

            }

            countDto.setSendAmount(sendAmount);
            countDto.setSendAmountMsg(sendAmountMsg);
            countDto.setSendType(sendType);
            countDto.setPayAmount(payAmount);
        }
        //重新计算DTO,最外层的实付金额
        Double payAmount = 0.00;
        for(SundayCountDto countDto:countTotalDto.getCounts()){
            payAmount+=countDto.getPayAmount().doubleValue();
        }
        countTotalDto.setPayAmount(new BigDecimal(payAmount));
        //返回要结算的购物车ID集合
       countTotalDto.setCartIds(cartIds);

        return countTotalDto;
    }
    /**
     *
     * @param memberId
     * @param productId
     * @param number
     * @param isUsedAiGou 是否使用爱购币,只针对shopId=0的直营商品
     * @param isUsedBalance 是否使用余额,只针对shopId=0的直营商品
     * @param teamIsJoin 是否参与拼团,只针对shopId=0的直营商品
     * @param teamGroupId 拼团组ID,只针对shopId=0的直营商品
     * @return
     */
    /*public SundayCountTotalDto countBuyNow(Long memberId,Long productId,Integer number,
                                           Integer isUsedAiGou,
                                           Integer isUsedBalance,
                                           Integer teamIsJoin,
                                           Long teamGroupId
    ){
        List<Long> productIds = Arrays.asList(new Long[]{productId});
        productIds.add(productId);
        List<Integer> numbers =Arrays.asList(new Integer[]{number});
        List<Long> cartIds= cartService.addCart(memberId,productIds ,numbers, SundayCommonConstants.cart_type_buy_now);
        return countCart(memberId,cartIds,SundayCommonConstants.cart_type_buy_now,isUsedAiGou,isUsedBalance,teamIsJoin,teamGroupId);
    }*/





}

